package interpreter.bytecodes;

import interpreter.VirtualMachine;
import java.util.NoSuchElementException;
import java.util.Vector;

/**
 *
 * @author bm
 */
public class PopByteCode extends ByteCode {
    private int elems;

    /**
     * Initializes the Pop byte code with exactly one argument
     */
    public void init( Vector<String> args ) {
        try {
            elems = Integer.parseInt( args.firstElement() );
        } catch( NumberFormatException nfe ) {
            // If bad format
            System.out.println("Bad format!");
            System.exit(-1);
        } catch( NoSuchElementException nse ) {
            // If empty argument
            System.out.println("Empty vector!");
            System.exit(-1);
        } catch( NullPointerException npe ) {
            // If argument missing
            System.out.println("Argument given = null.");
            System.exit(-1);
        }
    }

    /**
     * Action: Pop n elements off the top of the runtime stack
     *
     * @param rt the Virtual Machine reference
     */
    public void exec( VirtualMachine rt ) {
        // ERROR CHECK!
        if( rt.getStackSize() < elems ) {
            System.out.println("ERROR: Cannot pop " + elems + " elements off the stack.\nNot enough elements!");
            rt.haltProgram();
            return;
        }

        for( int i = 0; i < elems; i++) rt.popStack();
    }

    public Object getArgs() {
        return elems;
    }
}
